//
//  YGComposeViewController.swift
//  sinaWeiBoGui
//
//  Created by liyonggui on 16/5/21.
//  Copyright © 2016年 liyonggui. All rights reserved.
//

import UIKit

class YGComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = GlobalBKGColor
        
        setupNavigationBar()
        setupTextView()
        setupToolBar()
        
        // 监听键盘frame的值改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    // 已经显示时调用,键盘自动弹出
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 成为第一响应者
        textView.becomeFirstResponder()
    }
    
    // 移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 实现通知回调方法
    func willChangeFrame(notif: NSNotification) {
//        YGPrint(items: "\(notif)")
        // 键盘动画时间
        let duration = notif.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        // 最后的frame
        let frame = notif.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 计算toolBar底部的间距
        let bottomMargin = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            // 更新约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view).offset(bottomMargin)
            })
            // 刷新layout
            self.view.layoutIfNeeded()
        }
    }
    
    /// 设置toolBar
    private func setupToolBar() {
        view.addSubview(toolBar)
        
        // 添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        // 添加内容item
        // 每个item对应的图片名称
        let itemSettings = [
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_add_background", "action": "add"]
        ]
        
        // 创建空数组
        toolBar.items = [UIBarButtonItem]()
        var index = 0
        
        for dic in itemSettings {
            // 获取图片名称
            let imageName = dic["imageName"]!
            // 获取图片对应的点击事件
            let action = dic["action"]!
            
            // 创建 UIBarButtonItem
            let item = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action))
            
            // 设置tag
            item.customView?.tag = index
            
            toolBar.items?.append(item)
            
            // 创建弹簧
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            index++
        }
        // 删除最后一个弹簧
        toolBar.items?.removeLast()
    }
    
    // MARK: - 点击事件
    @objc private func picture() {
        YGPrint(items: "picture")
    }
    @objc private func trend() {
        YGPrint(items: "trend")
    }
    @objc private func mention() {
        YGPrint(items: "mention")
    }
    @objc private func emoticon() {
//        YGPrint(items: "emoticon")
        
        
        
        
        
    }
    @objc private func add() {
        YGPrint(items: "add")
    }
    
    /// 设置textView
    private func setupTextView() {
//        view.backgroundColor = UIColor.greenColor()
        // 添加都父容器
        view.addSubview(textView)
        
        // 设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    
    /// 设置NavigationBar
    private func setupNavigationBar() {
        // 左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        // 右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        setupTitleView()
    }
    
    /// 设置导航栏的标题
    private func setupTitleView() {
        let prefix = "发微博"
         // 获取用户名称
        if let name = YGUserAccountViewModel.sharedInstance.userAccount?.screen_name {
           
            let text = prefix + "\n" + name
            
            let label = UILabel()
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(13)
            label.numberOfLines = 0
            label.textAlignment = .Center
            
            // 创建属性文本
            let attrText = NSMutableAttributedString(string: text)
            // 获取用户名称范围
            let nameRange = (text as NSString).rangeOfString(name)
            // 属性文本添加属性
            attrText.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            attrText.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(11), range: nameRange)
            
            label.attributedText = attrText
            
            label.sizeToFit()
            navigationItem.titleView = label
            
        } else {
            // 没有用户名称
            navigationItem.title = prefix
        }
    }
    
    /// 发送微博
    @objc private func sendStatus() {
        YGPrint(items: "sendStatus")
    }
    /// 关闭控制器
    @objc private func close() {
//        YGPrint(items: "close")
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 懒加载
    /// textView
    private lazy var textView: YGPlaceholderTextView = {
        let tv = YGPlaceholderTextView()
        
        tv.backgroundColor = UIColor.greenColor()
        tv.font = UIFont.systemFontOfSize(composeTextFontSize)
        tv.placeholder = "请输入"
        // 代理
        tv.delegate = self
        
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.alwaysBounceVertical = true
        
        return tv
    }()
    
    /// toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()

}

// MARK: - 代理扩展 textView
extension YGComposeViewController: UITextViewDelegate {
    // 文本改变
    func textViewDidChange(textView: UITextView) {
        YGPrint(items: "\(textView.text)")
        
        // 切换导航栏的 发送 状态
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
























